<?php

namespace app\store\controller;

use app\common\exception\BaseException;
use app\common\service\qrcode\Collections;
use app\store\model\Setting as SettingModel;
use app\store\model\Wxapp as WxappModel;
use think\Cache;
use utils\Http;
/**
 * 小程序管理
 * Class Wxapp
 * @package app\store\controller
 */
class Wxapp extends Controller
{
    /**
     * 小程序设置
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function setting()
    {
        // 当前小程序信息
        $model = WxappModel::detail();

        if (!$this->request->isAjax()) {
            return $this->fetch('setting', compact('model'));
        }
        // 更新小程序设置

        if ($model->edit($this->postData('wxapp'))) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }




    /**
     * 生成二维码图片
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function qrcode()
    {
        if (!$this->request->isAjax()) {
            $code=db('wxapp')->where('wxapp_id',$this->getWxappId())->value('coll_code');

           if(isset($code) && $code!==0){
               $file_data=explode('/',$code);
               $qdata=[
                   'file'=>$code,
                   'name'=>end($file_data)
               ];

                return $this->fetch('qrcode', [
                    'data' =>$code,
                    'qdata'=> $qdata
                ]);
            }else{
                $data=$this->code($this->getWxappId());
                // 新增记录
                $param=$this->qrdown($data,$this->getWxappId());
                $file_data=explode('/',$param);
                $qdata=[
                    'file'=>$param,
                    'name'=>end($file_data)
                ];
                //写入数据表，收款二维码路劲
                db('wxapp')->where('wxapp_id',$this->getWxappId())->setField('coll_code',$param);
                return $this->fetch('qrcode', [
                    'data' =>$param,
                    'qdata'=>$qdata
                ]);
            }

        }
        return $this->renderError( '生成失败');

    }

    public function qrdown($params,$wxappId){

        $url = \think\Request::instance()->domain();
        $bigImgPath ='assets/common/img/back.png';
        $qCodePath =$params;
        $img = file_get_contents($bigImgPath);
        $bigImg = imagecreatefromstring($img);
        if(!file_exists($qCodePath)){
           sleep(3);
        }
        $qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
        list($qCodeWidth, $qCodeHight) = getimagesize($qCodePath);
        imagecopymerge($bigImg, $qCodeImg, 130, 180, 0, 0, $qCodeWidth, $qCodeHight, 100);
        list($bigWidth, $bigHight) = getimagesize($bigImgPath);
        header('Content-Type:image/png');

        $savepath="./code/shop/".$wxappId."/".time().mt_rand(111,999).".png";
//        if(!file_exists($savepath)){
//            //检查是否有该文件夹，如果没有就创建，并给予最高权限
//            mkdir($savepath, 755,true );
//        }
        imagepng($bigImg,$savepath);//推广二维码存到本地
        return $savepath=$url.substr($savepath, 1);

    }



    public function code($wxappId){
        $url = \think\Request::instance()->domain();
        //生成二维码 开始
        //配置APPID、APPSECRET
        $config=$this->wxConfig($wxappId);

        $cacheKey =$config['app_id'] . '@access_tokenapp';
       
        if (!Cache::get($cacheKey)) {
            // 请求API获取 access_token
            //获取access_token
            $ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$config['app_id']}&secret={$config['app_secret']}";

            $result =curlPost( $ACCESS_TOKEN );
            $response =json_decode($result, true);
            if (array_key_exists('errcode', $response)) {
                throw new BaseException(['msg' => "access_token获取失败，错误信息：{$result}"]);
            }
            // 写入缓存
            Cache::set($cacheKey, $response['access_token'], 6000);    // 7000
        }else{
            $ACCESS_TOKEN = Cache::get($cacheKey);
        }

          
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $param =json_encode(array('scene'=>2,'wxapp_id' =>$wxappId,"path"=>"pages/face/index","width"=>430));
        $baseUrl = "./code/shop/".$wxappId;
        if(!file_exists($baseUrl)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($baseUrl, 755,true );
        }
        $imgurl = "./code/shop/".$wxappId."/".$wxappId.".png";;
        //POST参数
        $result =curlPost($qcode,$param,"POST");
        file_put_contents($imgurl, $result);
        resize_image($imgurl, $imgurl, 430, 430);
        return $url.substr($imgurl, 1);
        //生成二维码 结束
        }
    /**
     * @function 发起请求所必须的配置参数
     * @return mixed
     * @param $wxappId int
     */
    private function wxConfig($wxappId)
    {
        $wxConfigs= \app\common\model\Wxapp::getWxappCache($wxappId);
        $wxConfig['app_id'] = $wxConfigs['app_id'];
        $wxConfig['app_secret'] = $wxConfigs['app_secret'];
        return $wxConfig;
    }


}
